import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface KeyboardConfig {
    // 防抖延迟时间
    debounceDelay: number
    // 是否自动启动监听
    autoStart: boolean
    // 是否在页面隐藏时停止监听
    stopOnHide: boolean
    // 键盘高度阈值，小于此值认为键盘已收起
    heightThreshold: number
}

export interface KeyboardHistory {
    timestamp: number
    height: number
    action: 'show' | 'hide'
}

export const useKeyboardStore = defineStore('keyboard', () => {
    // 键盘状态
    const height = ref(0)
    const isVisible = ref(false)
    const isListening = ref(false)

    // 键盘配置
    const config = ref<KeyboardConfig>({
        debounceDelay: 100,
        autoStart: false,
        stopOnHide: true,
        heightThreshold: 50
    })

    // 键盘历史记录（最多保留10条）
    const history = ref<KeyboardHistory[]>([])

    // 计算属性
    const keyboardInfo = computed(() => ({
        height: height.value,
        isVisible: isVisible.value,
        isListening: isListening.value,
        lastUpdate: history.value[0]?.timestamp || 0
    }))

    // 平台判断
    const isApp = computed(() => {
        // #ifdef APP-PLUS
        return true
        // #endif
        // #ifndef APP-PLUS
        return false
        // #endif
    })

    // 防抖定时器
    let debounceTimer: number | null = null

    // 监听器回调函数
    const onKeyboardHeightChange = (res: { height: number }) => {
        // 清除之前的定时器
        if (debounceTimer) {
            clearTimeout(debounceTimer)
        }

        // 防抖处理
        debounceTimer = setTimeout(() => {
            const newHeight = res.height || 0
            const wasVisible = isVisible.value
            const nowVisible = newHeight >= config.value.heightThreshold

            // 更新状态
            height.value = newHeight
            isVisible.value = nowVisible

            // 记录历史
            const historyItem: KeyboardHistory = {
                timestamp: Date.now(),
                height: newHeight,
                action: nowVisible ? 'show' : 'hide'
            }

            // 添加到历史记录（保留最新10条）
            history.value.unshift(historyItem)
            if (history.value.length > 10) {
                history.value.pop()
            }

            // console.log(`Keyboard ${nowVisible ? 'shown' : 'hidden'} - Height: ${newHeight}px`)

            // 触发状态变化事件（可以在这里添加更多逻辑）
            if (wasVisible !== nowVisible) {
                emitKeyboardStateChange(nowVisible, newHeight)
            }
        }, config.value.debounceDelay) as unknown as number
    }

    // 键盘状态变化事件（可扩展）
    const emitKeyboardStateChange = (visible: boolean, keyboardHeight: number) => {
        // 这里可以添加全局事件发布逻辑
        const event = {
            type: 'keyboardStateChange',
            visible,
            height: keyboardHeight,
            timestamp: Date.now()
        }

        // console.log('Keyboard state changed:', event)
        // 可以在这里发布到全局事件总线
    }

    // 启动键盘监听
    const startListening = () => {
        if (!isApp.value) {
            console.warn('Keyboard listening is only supported on App platform')
            return false
        }

        if (typeof uni.onKeyboardHeightChange !== 'function') {
            console.error('uni.onKeyboardHeightChange is not available')
            return false
        }

        if (isListening.value) {
            console.warn('Keyboard listener is already active')
            return true
        }

        try {
            uni.onKeyboardHeightChange(onKeyboardHeightChange)
            isListening.value = true
            // console.log('Keyboard listener started successfully')
            return true
        } catch (error) {
            // console.error('Failed to start keyboard listener:', error)
            return false
        }
    }

    // 停止键盘监听
    const stopListening = () => {
        if (!isApp.value) {
            return true
        }

        if (typeof uni.offKeyboardHeightChange !== 'function') {
            console.error('uni.offKeyboardHeightChange is not available')
            return false
        }

        if (!isListening.value) {
            return true
        }

        try {
            uni.offKeyboardHeightChange(onKeyboardHeightChange)
            isListening.value = false

            // 清除防抖定时器
            if (debounceTimer) {
                clearTimeout(debounceTimer)
                debounceTimer = null
            }

            // console.log('Keyboard listener stopped successfully')
            return true
        } catch (error) {
            // console.error('Failed to stop keyboard listener:', error)
            return false
        }
    }

    // 重置键盘状态
    const resetState = () => {
        height.value = 0
        isVisible.value = false
        history.value = []

        if (debounceTimer) {
            clearTimeout(debounceTimer)
            debounceTimer = null
        }

        // console.log('Keyboard state reset')
    }

    // 更新配置
    const updateConfig = (newConfig: Partial<KeyboardConfig>) => {
        config.value = { ...config.value, ...newConfig }
        // console.log('Keyboard config updated:', config.value)
    }

    // 获取键盘适配样式
    const getAdaptiveStyle = (options?: {
        type?: 'margin' | 'padding' | 'height'
        direction?: 'bottom' | 'top'
    }) => {
        const { type = 'margin', direction = 'bottom' } = options || {}

        return computed(() => {
            const style: Record<string, string> = {}

            if (isVisible.value && height.value > 0) {
                const property = `${type}-${direction}`
                style[property] = `${height.value}px`
            } else {
                const property = `${type}-${direction}`
                style[property] = '0px'
            }

            return style
        })
    }

    // 获取统计信息
    const getStatistics = () => {
        const showCount = history.value.filter(h => h.action === 'show').length
        const hideCount = history.value.filter(h => h.action === 'hide').length
        const avgHeight = history.value.length > 0
            ? history.value.reduce((sum, h) => sum + h.height, 0) / history.value.length
            : 0

        return {
            totalEvents: history.value.length,
            showCount,
            hideCount,
            averageHeight: Math.round(avgHeight),
            isCurrentlyListening: isListening.value,
            currentHeight: height.value,
            isCurrentlyVisible: isVisible.value
        }
    }

    return {
        // 状态
        height,
        isVisible,
        isListening,
        config,
        history,
        keyboardInfo,
        isApp,

        // 方法
        startListening,
        stopListening,
        resetState,
        updateConfig,
        getAdaptiveStyle,
        getStatistics
    }
}, {
    persist: {
        key: 'keyboard-store',
    // 只持久化配置，不持久化运行时状态
    paths: ['config']
  }
})

export default useKeyboardStore